import { generateUserAgent } from './user-agent'

export interface BrowserFingerprint {
  userAgent: string
  acceptLanguage: string
  secChUa?: string
  secChUaMobile?: string
  secChUaPlatform?: string
  device: 'desktop' | 'mobile'
  platform: 'windows' | 'mac' | 'linux' | 'android'
  browser: 'chrome' | 'edge'
  major: number
}

function prng(): () => number {
  let x = (Math.random() * 0x100000000) >>> 0
  return () => {
    x = (x * 1664525 + 1013904223) >>> 0
    return x / 0x100000000
  }
}

function pick<T>(arr: T[], r: () => number): T { return arr[Math.floor(r() * arr.length)] }

/**
 * 为 Chromium 场景生成一致的随机浏览器指纹（避免 iOS/mac Safari 与 UA-CH 不一致）。
 * - 平台：windows | mac | linux | android（排除 iOS）
 * - 浏览器：chrome | edge（与 Chromium 引擎一致）
 * - 生成匹配的 sec-ch-ua / platform / mobile
 */
export function generateRandomFingerprint(): BrowserFingerprint {
  const rnd = prng()
  const device = pick(['desktop', 'mobile'] as const, rnd)
  const platform = device === 'mobile' ? 'android' : pick(['windows', 'mac', 'linux'] as const, rnd)
  const browser = pick(['chrome', 'edge'] as const, rnd)

  // 生成 UA（仅选用 Chromium 家族，避免与 UA-CH 冲突）
  const ua = generateUserAgent({
    device,
    platform,
    browser,
  })

  // 从 UA 中解析主版本号（Chrome/Edg）
  let major = 120
  try {
    const m = ua.match(/(?:Chrome|Edg)\/(\d{2,3})\./)
    if (m)
      major = Math.max(90, Number.parseInt(m[1], 10))
  }
  catch {}

  // UA-CH 品牌串（示例："Chromium";v="125", "Google Chrome";v="125", "Not=A?Brand";v="24")
  const brandChrome = `"Chromium";v="${major}", "Google Chrome";v="${major}", "Not=A?Brand";v="24"`
  const brandEdge = `"Chromium";v="${major}", "Microsoft Edge";v="${major}", "Not=A?Brand";v="24"`
  const secChUa = browser === 'edge' ? brandEdge : brandChrome

  // 平台映射
  const platformLabel = platform === 'windows'
    ? '"Windows"'
    : platform === 'mac'
      ? '"macOS"'
      : platform === 'linux'
        ? '"Linux"'
        : '"Android"'

  // 是否移动端
  const secChUaMobile = device === 'mobile' ? '?1' : '?0'

  // 语言：保持与现有默认一致，避免 UI 波动；如需可扩展随机化
  const acceptLanguage = 'zh-CN,zh;q=0.9,en;q=0.8'

  return {
    userAgent: ua,
    acceptLanguage,
    secChUa,
    secChUaMobile,
    secChUaPlatform: platformLabel,
    device,
    platform,
    browser,
    major,
  }
}
